import CryptoJs from 'crypto-js'
import { DES_KEY } from '../app/config'

/**
 * md5加密
 */
export const md5 = (message: string | CryptoJs.lib.WordArray) => {
  return CryptoJs.MD5(message).toString().toUpperCase()
}

/**
 * DES加密
 */
export const enDES = (message: string | CryptoJs.lib.WordArray) => {
  const keyHex = CryptoJS.enc.Utf8.parse(DES_KEY)
  const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  })
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64)
}

/**
 * DES解密
 */
export const deDES = (ciphertext: string) => {
  const keyHex = CryptoJS.enc.Utf8.parse(DES_KEY)
  const ciphertextBytes = CryptoJS.enc.Base64.parse(ciphertext)
  const options = { ciphertext: ciphertextBytes } as CryptoJs.lib.CipherParams
  const decrypted = CryptoJS.DES.decrypt(options, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  })
  return decrypted.toString(CryptoJS.enc.Utf8)
}
